package com.sky.controller.admin;

import com.sky.properties.MinioProperties;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import com.sky.utils.MinioUtils;
import io.minio.ObjectWriteResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.UUID;

/*
* 公共接口
* */
@RestController
@RequestMapping("/admin/common")
@Api(tags = "公共接口")
@Slf4j
public class CommonController {

    @Resource
    AliOssUtil aliOssUtil;

    @Resource
    MinioUtils minioUtils;

    @Resource
    MinioProperties properties;

    @ApiOperation("文件上传")
    @PostMapping("upload")
    @SneakyThrows
    public Result upload(MultipartFile file){
        log.info("开始文件上传：{}" , file);
        try {
            //获取传递过来文件的后缀
            String filename = file.getOriginalFilename();
            String extension = filename.substring(filename.lastIndexOf("."));
            String newFileName = UUID.randomUUID() + extension;
//            String upload = aliOssUtil.upload(file.getBytes(), newFileName);
            ObjectWriteResponse put = minioUtils.putObject(properties.getBucketName(), file, newFileName, "image/png");
            String objectUrl = minioUtils.getObjectUrl(properties.getBucketName(), newFileName);
            System.out.println(objectUrl);
            return Result.success(objectUrl);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
